<?php

namespace App\Kuafu\Order\Validate;

use App\Kuafu\Order\Enum\OrderCodeEnum;
use App\Kuafu\Order\Exceptions\OrderException;
use App\Kuafu\Order\Model\OrderSplitModel;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\Base\Validate\BaseValidate;

class OrderValidate extends BaseValidate
{
    public static function getOrderById($data)
    {
        $rules    = [
            'orderId' => [
                'required',
                'integer',
                'min:0',
                function ($attribute, $value, $fail) use ($data) {
                    if (!OrderSplitModel::suffix($data['shopId'])->query()
                                   ->where([
                                       'orderId' => $data['orderId'],
                                       'brandId' => $data['brandId'],
                                       'shopId'  => $data['shopId']
                                   ])
                                   ->first()) {
                        $fail("订单信息不存在");
                    }
                }
            ],
        ];
        $messages = [];

        return self::validateCheck($data, $rules, $messages);
    }

    public static function getOrderList($data)
    {
        $rules    = [
            'pageSize' => self::commonRules('pageSize'),
            'pageNum'  => self::commonRules('pageNum'),
        ];
        $messages = [];

        return self::validateCheck($data, $rules, $messages);
    }

    /**
     * 校验菜品状态
     *
     * @param $data
     * @return void
     * @throws OrderException
     */
    public static function checkProductStatus($data)
    {
        // 获取商品估清/下架数据
        $productStatus = ShopService::sGetStatusList($data['shopId'], $data['productIds']);

        if (!$productStatus->isEmpty()) {
            // 存在估清商品
            $downProductIds = $productStatus->pluck('productId');

            foreach ($downProductIds as $v) {
                $errorMsg .= $data['product'][$v]['name'] . ' ';
            }

            $errorMsg .= '商品状态为下架或者估清状态,请重新下单.';
            throw new OrderException(OrderCodeEnum::ERR_ORDER_ADD_ERROR, $errorMsg);
        }
    }


    public static function setOrder($data)
    {
        $rules    = [
            'id' => 'required|integer|min:0',
        ];
        $messages = [];

        return self::validateCheck($data, $rules, $messages);
    }

    public static function delOrder($data)
    {
        $rules    = [
            'id' => 'required|integer|min:0',
        ];
        $messages = [];

        return self::validateCheck($data, $rules, $messages);
    }

    public static function patchOrderStatus($data)
    {
        $rules    = [
            'id'     => 'required|integer|min:0',
            'status' => 'required|integer|between:0,1',
        ];
        $messages = [];

        return self::validateCheck($data, $rules, $messages);
    }

}
